package com.codingvip.concurrent;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyList {

    public static void main(String[] args) {
        //creating CopyOnWriteArrayList
//        List<String> carList = new ArrayList<String>();
        List<String> carList = new CopyOnWriteArrayList<String>();
        carList.add("Audi");
        carList.add("Jaguar");
        carList.add("Mini Cooper");
        carList.add("BMW");
        Thread t1 = new Thread(new ItrClass(carList));
        Thread t2 = new Thread(new ModClass(carList));
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("List elements in Main- " + carList);
    }
}

// Thread class for iteration
class ItrClass implements Runnable {
    List<String> carList;

    public ItrClass(List<String> carList) {
        this.carList = carList;
    }

    @Override
    public void run() {
        Iterator<String> i = carList.iterator();
        while (i.hasNext()) {
            System.out.println(i.next());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}

//Thread class for modifying list
class ModClass implements Runnable {
    List<String> carList;

    public ModClass(List<String> carList) {
        this.carList = carList;
    }

    @Override
    public void run() {
        System.out.println("Adding new value to the list");
        carList.add("Mercedes");
    }
}